﻿Option Explicit On
Option Strict On

Imports LogginsLogDSTableAdapters

Partial Class Account_Register
    Inherits System.Web.UI.Page
    Dim u As MembershipUser
    Dim invitation As Boolean = False
    Dim emailstring As String = ""
    Dim loginoccurred As Boolean
    Dim validfordaysnum As Integer
    Dim daterequesteddate As DateTime
    Dim personidstring As Integer = 0
    Dim EntityId As Integer = 0
    Dim associateidstring As Integer = 0

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'RegisterUser.ContinueDestinationPageUrl = Request.QueryString("ReturnUrl")
        If Not Request.QueryString("invitation") Is Nothing Then

            Dim strAlreadyConfirmedMessage As String = "Sorry, it seems like your membership has already been confirmed. "
            Dim strAlreadyExpired As String = "Sorry, it seems like your membership invitation has already expired. Please ask your sponsor to request another."

            Dim invitationguid As Guid
            Try
                invitationguid = New Guid(Request.QueryString("invitation"))
            Catch ex As Exception
                'Stop an error being generated if the users tampers with the string and it is not a guid
                'Log out the user here and dump them back to the outer home page without any info if it is not a guid
            End Try

            Dim newpersonassociaterequestemailTA As New LogginsLogDSTableAdapters.usp_PersonAssociateRequestTableAdapter()
            Dim newpersonassociaterequestemailDT As LogginsLogDS.usp_PersonAssociateRequestDataTable

            Try
                newpersonassociaterequestemailDT = newpersonassociaterequestemailTA.GetData(invitationguid)
            Catch ex As Exception
                Throw ex
            End Try


            For Each newpersonassociaterequestemailRow As LogginsLogDS.usp_PersonAssociateRequestRow In newpersonassociaterequestemailDT
                personidstring = newpersonassociaterequestemailRow.PersonId  'Get the personid that requested/invited this Associate
                EntityId = newpersonassociaterequestemailRow.RequestedForEntityId
                emailstring = newpersonassociaterequestemailRow.RequestedForEmail
                loginoccurred = newpersonassociaterequestemailRow.LoginOccurred
                validfordaysnum = newpersonassociaterequestemailRow.ValidForDays
                daterequesteddate = newpersonassociaterequestemailRow.DateRequested
                associateidstring = newpersonassociaterequestemailRow.Id
            Next

            Dim days As Integer = CInt((DateTime.Now.AddDays(0 - validfordaysnum).Subtract(daterequesteddate)).TotalDays)

            If loginoccurred Then
                lblInvitationMessage.Text = strAlreadyConfirmedMessage
                InvitationFailModalPopupExtender.Show()
            ElseIf days > 0 Then
                lblInvitationMessage.Text = strAlreadyExpired
                InvitationFailModalPopupExtender.Show()

            Else
                Dim txtEmail As TextBox = DirectCast(RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("Email"), TextBox)
                txtEmail.Text = emailstring
                txtEmail.ReadOnly = True
                lblInvitationMessage.Text = ""

            End If

        End If

    End Sub

    Protected Sub RegisterUser_CreatedUser(ByVal sender As Object, ByVal e As EventArgs) Handles RegisterUser.CreatedUser

        FormsAuthentication.SetAuthCookie(RegisterUser.UserName, False)
        u = Membership.GetUser(RegisterUser.UserName)

        Dim virtualurl As String = ("http://" + HttpContext.Current.Request.Url.Authority.ToString() + "/" + _
            HttpContext.Current.Request.Url.Segments(1).ToString() + "Account/Activate.aspx?id=").Replace("Account/Account/", "Account/")
        Dim virtualurl1 As String = ("http://" + HttpContext.Current.Request.Url.Authority.ToString() + "/" + _
            HttpContext.Current.Request.Url.Segments(1).ToString() + "private/secure_admin/default.aspx?id=").Replace("private/private/", "private/")

        Dim strMailFrom As String = ConfigurationManager.AppSettings("smtpmailfrom").ToString()
        Dim strMailTo As String = ConfigurationManager.AppSettings("accountapprovalemail").ToString()
        Dim strApprovalEmail As String = strMailTo
        Dim sendemail As New SendEmailViaGoogle()

        Dim strMessage As String = "FYI: A new user [" + u.UserName + "] has registered. " + u.ProviderUserKey.ToString() + "</br>"
        'strMessage += "FYI: A new user [" + u.UserName + "] has registered. " + virtualurl1 + u.ProviderUserKey.ToString() + "</br>"
        Dim strSubject As String = "Account Sign-up/Registration"

        Dim strRecipient As String = strApprovalEmail

        Try

            'Send the email to the account approver
            sendemail.SendEmail(strMailFrom, strMailTo, strSubject, strMessage)

        Catch ex As Exception

            'Do something with this error, 
            'Maybe send it back to be handled in global.asax
            Throw ex

        End Try
        'Add user to the Role named AwaitingApproval
        'Roles.AddUserToRole(u.UserName, "AwaitingApproval")
        u.IsApproved = False
        If Not Request.QueryString("invitation") Is Nothing Then
            invitation = True
        End If

        Membership.UpdateUser(u)
        Dim chkMailList As CheckBox = DirectCast(RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("chkMailList"), CheckBox)
        Dim addnewusercheckTA As New LogginsLogDSTableAdapters.SPTableAdapter
        Dim personID As Integer?

        'This controls what checks the user has to go through on the way to the Inner Home Page
        'AccountInCredit ApprovalRequired RegistrationComplete EmailConfirmed AwaitingApproval AccountActive Active UserRoleSet AssociatedEntitySet UserPlanChosen
        '1               1                0                    0              1                1             1      0           0                   0
        Try
            Dim gu As Guid = CType(u.ProviderUserKey, Guid)

            If Not invitation Then  'Not an Associate Login
                addnewusercheckTA.usp_UserCheckInsert(gu, True, True, False, False, True, True, False, True, False, False, False)

            Else
                'An Associate is in the house!
                addnewusercheckTA.usp_UserCheckInsert(gu, True, False, False, True, False, True, False, True, True, True, False)
            End If

            addnewusercheckTA.usp_AddNewPerson(gu, String.Empty, _
                                               String.Empty, String.Empty, String.Empty, String.Empty, _
                                               String.Empty, String.Empty, String.Empty, CType(1, Boolean), _
                                               CType(1, Boolean), chkMailList.Checked, personID)

        Catch ex As Exception
            Throw ex

        End Try
        If Not invitation Then
            Try
                Dim justinsertedentity As Integer?
                Try
                    'Dim num2 As Integer = CInt(addnewusercheckTA.usp_PersonEntity_Insert(personID, "", "", "", Date.Now, 1, CType(1, Boolean?)))
                    Dim entityTA As New LogginsLogDSTableAdapters.usp_EntityTableAdapter()
                    entityTA.Insert(String.Empty, String.Empty, Date.Now, String.Empty, 0, True, justinsertedentity)

                Catch ex As Exception
                    Throw ex
                End Try

                Dim personentitypeexpTA As New LogginsLogDSTableAdapters.usp_PersonEntity_ExpTableAdapter()
                personentitypeexpTA.Insert(personID, justinsertedentity, True)
            Catch ex As Exception
                Throw ex
            End Try
        End If
        '<<<<<<< .mine
        '        'Response.Redirect("~/private/")
        '=======
        If Not Request.QueryString("invitation") Is Nothing Then
            Roles.AddUserToRole(u.UserName, "ListAssociate")
            Roles.RemoveUserFromRole(u.UserName, "AwaitingApproval")
            u.IsApproved = True
            Membership.UpdateUser(u)

            Dim newpersonassociaterequestid As Integer
            Dim newassociaterequestid As Integer
            Dim invitorpersonid As Integer

            Dim invitationguid As Guid
            Try
                invitationguid = New Guid(Request.QueryString("invitation"))
            Catch ex As Exception
                'Stop an error being generated if the users tampers with the string and it is not a guid
                'Log out the user here and dump them back to the outer home page without any info if it is not a guid
                FormsAuthentication.SignOut()
                HttpContext.Current.Response.Redirect("~/Default.aspx")
            End Try

            Dim newpersonassociaterequestTA As New LogginsLogDSTableAdapters.usp_PersonAssociateRequestTableAdapter()
            Dim newpersonassociaterequestDT As LogginsLogDS.usp_PersonAssociateRequestDataTable

            Try
                newpersonassociaterequestDT = newpersonassociaterequestTA.GetData(invitationguid)
            Catch ex As Exception
                Throw ex
            End Try

            For Each newpersonassociaterequestRow As LogginsLogDS.usp_PersonAssociateRequestRow In newpersonassociaterequestDT
                newpersonassociaterequestid = newpersonassociaterequestRow.Id
                newassociaterequestid = newpersonassociaterequestRow.RequestedForEntityId
                invitorpersonid = newpersonassociaterequestRow.PersonId
            Next
            'Dim newpersonassociaterequestid As Integer = Convert.ToInt32(From q In newpersonassociaterequestDT.AsEnumerable() Where q.AssociateToken.Equals(Request.QueryString("invitation")) Select q.Id)

            Dim newpersonassociaterequestactiveupdateTA As New LogginsLogDSTableAdapters.SPTableAdapter()
            newpersonassociaterequestactiveupdateTA.usp_PersonAssociateRequestActiveUpdate(newpersonassociaterequestid)

            Dim personsiteroleID As Integer?
            Dim newpersonsiteroleTA As New LogginsLogDSTableAdapters.usp_PersonSiteRoleTableAdapter()
            Dim newnow As Integer = newpersonsiteroleTA.Insert(personID, False, False, True, False, True, personsiteroleID)

            Dim personassociateentityextTA As New LogginsLogDSTableAdapters.usp_PersonAssociateEntity_ExpTableAdapter
            Dim mynum = personassociateentityextTA.Insert(personID, newassociaterequestid, True)
            'Dim newpersonassociateextTA As New usp_
            'newpersonassociateextTA.Insert(newpersonassociaterequestid, )

            Dim emailverupdate As New LogginsLogDSTableAdapters.SPTableAdapter()
            emailverupdate.EmailVerification(CType(u.ProviderUserKey, Global.System.Guid))
            Dim personTA As New LogginsLogDSTableAdapters.PersonTableAdapter()
            Dim personDT As LogginsLogDS.PersonDataTable

            Try
                personDT = personTA.GetData(Nothing)
            Catch ex As Exception
                Throw ex
            End Try
            Try
                Dim getaassociatepersonid As New GetPersonIdFromUserId()
                Dim updatepersonassociateTA As New LogginsLogDSTableAdapters.SPTableAdapter()
                updatepersonassociateTA.usp_Update_PersonAssociateRequest_AssociateId(emailstring, _
                                                                                      personidstring, _
                                                                                      getaassociatepersonid.GetPersonId(CType(u.ProviderUserKey, Guid)))
            Catch ex As Exception
                Throw ex
            End Try

            Dim x As Guid = (From person In personDT.AsEnumerable() Where person.Id = invitorpersonid Select person.UserId).FirstOrDefault()
            u = Membership.GetUser(x)
            Dim invitesender As String = "Dear " + u.UserName + Environment.NewLine
            invitesender += "This email is to let you know that an account has been created for the individual you requested. Please note that they will be able to log in as long as your account remains active." + Environment.NewLine
            invitesender += "Site Administrator"

            Try

                'Send the email to the account approver
                sendemail.SendEmail(strMailFrom, u.Email, "Account has been created for the individual you requested", invitesender)

            Catch ex As Exception

                'Do something with this error, 
                'Maybe send it back to be handled in global.asax
                Throw ex

            End Try

            'HttpContext.Current.Response.Redirect("~/private/Default.aspx")
        Else
            RegistrationSuccessPopupExtender.Show()

        End If

        Session("UserName1") = u.UserName

        '>>>>>>> .r29
    End Sub

    Protected Sub RegisterUser_CreatingUser(sender As Object, e As System.Web.UI.WebControls.LoginCancelEventArgs) Handles RegisterUser.CreatingUser
        'Page.Validate()
        If Page.IsValid Then
            lblResult.Text = "+"
            lblResult.ForeColor = Drawing.Color.Green

        Else
            lblResult.Text = "-"
            lblResult.ForeColor = Drawing.Color.Red
            e.Cancel = True
        End If

        Dim chkAgreed As CheckBox = DirectCast(RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("chkAgree"), CheckBox)
        Dim litError As Label = DirectCast(RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("lblAgreed"), Label)
        If Not chkAgreed.Checked Then
            litError.Text = "You must agree to the Terms and Conditions"
            e.Cancel = True
        End If
    End Sub

    Protected Sub RegisterUser_CreateUserError(sender As Object, e As System.Web.UI.WebControls.CreateUserErrorEventArgs) Handles RegisterUser.CreateUserError
        'Response.Redirect("~/Account/RegisterError.aspx")
        RegisterErrorModalPopupExtender.Show()
    End Sub

    Protected Sub RegisterUser_SendingMail(sender As Object, e As System.Web.UI.WebControls.MailMessageEventArgs) Handles RegisterUser.SendingMail
        u = Membership.GetUser(RegisterUser.UserName)
        Roles.IsUserInRole(u.UserName, "ListAssociate")
        If Not Roles.IsUserInRole(u.UserName, "ListAssociate") Then
            ' Set MailMessage fields.
            e.Message.IsBodyHtml = False
            e.Message.Subject = "New User Registration."
            ' Replace placeholder text in message body with information 
            ' provided by the user.
            Dim virtualurl As String = ("http://" + HttpContext.Current.Request.Url.Authority.ToString() + "/" + _
                HttpContext.Current.Request.Url.Segments(1).ToString() + "Account/Activate.aspx?id=").Replace("Account/Account/", "Account/")
            e.Message.Body = e.Message.Body.Replace("<%link%>", virtualurl + u.ProviderUserKey.ToString())
            'e.Message.Body = e.Message.Body.Replace("<%PasswordAnswer%>", Createuserwizard1.Answer)
            'Response.Redirect("~/account/RegisterSuccess.aspx")

            Try
                Dim emaillog As New LogginsLogDSTableAdapters.SPTableAdapter()
                emaillog.usp_MembershipEmailsOutgoingLogInsert(e.Message.From.Address, e.Message.To.FirstOrDefault.Address, e.Message.Subject, e.Message.Body.ToString(), DateTime.Now)
            Catch ex As Exception
                Throw ex
            End Try
        Else
            AccRegistrationSuccessModalPopupExtender.Show()
            e.Cancel = True
        End If
    End Sub

    Protected Sub RegisterUser_ActiveStepChanged(sender As Object, e As System.EventArgs) Handles RegisterUser.ActiveStepChanged
        If RegisterUser.ActiveStepIndex = 1 Then
            Recaptcha1.Visible = False
        End If
    End Sub

    Protected Sub btnCancel_Click(sender As Object, e As System.EventArgs) Handles btnCancel.Click
        If Not Request.QueryString("invitation") Is Nothing Then
            HttpContext.Current.Response.Redirect("~/private/default.aspx")

        Else
            FormsAuthentication.SignOut()
            HttpContext.Current.Response.Redirect("~/Default.aspx")

        End If

    End Sub

    Protected Sub btnCancelInvitationFail_Click(sender As Object, e As System.EventArgs) Handles btnCancelInvitationFail.Click
        HttpContext.Current.Response.Redirect("~/Default.aspx")
    End Sub

    Protected Sub btnAccRegistrationSuccessClose_Click(sender As Object, e As System.EventArgs) Handles btnAccRegistrationSuccessClose.Click
        HttpContext.Current.Response.Redirect("~/private/default.aspx")
    End Sub
End Class
